<?php

namespace app\api\model;

class UserData extends Common
{
    static public function createData($user_id, $money, $field)
    {
        if ($money > 0) {
            $UserData = new UserData;

            $result = $UserData->where(['user_id' => $user_id])->find();

            if (!$result) {
                $create = ['user_id' => $user_id, $field => $money];

                if ($field == 'income') {
                    $create['income_today'] = $money;
                    $create['income_time'] = time();
                }

                $UserData->create($create);
            } else {
                if ($field == 'income') {
                    $update = [
                        'id' => $result['id'],
                        $field => $result[$field] + $money,
                    ];
    
                    $date = date('Y-m-d');
    
                    $today_start = strtotime($date);
                    $yesterday_start = strtotime('-1 day', strtotime($date));
    
                    if ($result['income_time'] >= $today_start) { // 今天非第一笔
                        $update['income_today'] = $result['income_today'] + $money;
                    } else if ($result['income_time'] >= $yesterday_start) { // 今天第一笔
                        $update['income_today'] = $money;
                        $update['income_yesterday'] = $result['income_today'];
                    } else {
                        $update['income_today'] = $money;
                        $update['income_yesterday'] = 0;
                    }
    
                    $update['income_time'] = time();
    
                    $UserData->update($update);
                } else {
                    $UserData->where(['id' => $result['id']])->setInc($field, $money);
                }
            }
        }
    }
}
